package com.bitin.module.misc.domain.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class District implements Serializable {

    private String citycode;
    private String adcode;
    private String name;
    private String center;
    private Level level;
    private List<District> districts;

    public Region toRegion(){

        if(CollectionUtils.isNotEmpty(getDistricts())){
            switch (getDistricts().stream().findFirst().get().getLevel()){
                case street:
                    AtomicInteger index = new AtomicInteger(1);
                    this.districts.forEach(district -> {
                        String code = String.format("%s%02d", district.getAdcode(), index.get());
                        district.setAdcode(code);
                        index.getAndIncrement();
                    });
                    break;
                default:
            }
        }

        int length = getCitycode().replaceAll("]", "").length();

        return new Region(
                getAdcode(), getName(), (length == 1) ? null : getCitycode(), getCenter(), getLevel(),
                Optional.ofNullable(getDistricts())
                        .map(container -> container.stream().map(District::toRegion).collect(Collectors.toList()))
                        .orElse(null)
        );
    }
}
